package com.sbhotel.chotellauncher.util;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;

import com.sbhotel.chotellauncher.MyApplication;
import com.sbhotel.chotellauncher.callback.PingCallbackListener;
import com.sbhotel.chotellauncher.constant.Constants;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.lang.reflect.Method;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

public class Utils {

    public static void doPingAsync(final PingCallbackListener listener) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                boolean result = ping();
                if(listener != null) {
                    listener.onPingFinish(result);
                }
            }
        }).start();
    }

    public static final boolean ping() {

        String result = null;
        try {
            String ip = "www.baidu.com";// ping 的地址，可以换成任何一种可靠的外网
            Process p = Runtime.getRuntime().exec("ping -c 3 -w 100 " + ip);// ping网址3次
            // 读取ping的内容，可以不加
            InputStream input = p.getInputStream();
            BufferedReader in = new BufferedReader(new InputStreamReader(input));
            StringBuffer stringBuffer = new StringBuffer();
            String content = "";
            while ((content = in.readLine()) != null) {
                stringBuffer.append(content);
            }
            Log.d(Constants.LOG_TAG, "-- ping -- result content : " + stringBuffer.toString());
            // ping的状态
            int status = p.waitFor();
            if (status == 0) {
                result = "success";
                return true;
            } else {
                result = "failed";
            }
        } catch (IOException e) {
            result = "IOException";
        } catch (InterruptedException e) {
            result = "InterruptedException";
        } finally {
            Log.d(Constants.LOG_TAG, "-- ping -- result = " + result);
        }
        return false;
    }

    //检查wifi是否连接
    public static boolean isWifiConnected(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (cm != null) {
            NetworkInfo networkInfo = cm.getActiveNetworkInfo();
            if (networkInfo != null) {
                return networkInfo.isConnected();
            }
        }
        return false;
    }

    public static String getMac() {
        String macSerial = "";
        String str = "";

        try {
            Process pp = Runtime.getRuntime().exec("cat /sys/class/net/wlan0/address ");
            InputStreamReader ir = new InputStreamReader(pp.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);

            for (; null != str; ) {
                str = input.readLine();
                if (str != null) {
                    macSerial = str.trim();// 去空格
                    break;
                }
            }
        } catch (IOException ex) {
            // 赋予默认值
            ex.printStackTrace();
        }
        return macSerial;
    }

    public static final String getMac2() {
        byte[] mac = null;
        StringBuffer sb = new StringBuffer();
        try {
            Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
            while (netInterfaces.hasMoreElements()) {
                NetworkInterface ni = netInterfaces.nextElement();
                Enumeration<InetAddress> address = ni.getInetAddresses();
                while (address.hasMoreElements()) {
                    InetAddress ip = address.nextElement();
                    if (ip.isAnyLocalAddress() || !(ip instanceof Inet4Address) || ip.isLoopbackAddress())
                        continue;
                    if (ip.isSiteLocalAddress())
                        mac = ni.getHardwareAddress();
                    else if (!ip.isLinkLocalAddress()) {
                        mac = ni.getHardwareAddress();
                        break;
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        if(mac != null){
            for(int i=0 ;i<mac.length ;i++){
                sb.append(parseByte(mac[i]));
            }
            return (sb.substring(0, sb.length()-1)).toUpperCase();
        }else{
            return "";
        }
    }
    private static String parseByte(byte b) {
        String s = "00" + Integer.toHexString(b)+":";
        return s.substring(s.length() - 3);
    }

    public static String getDeviceUn(Context context) {
        return (String) SPUtil.get(context, Constants.SP_KEY_DEVICE_UN_CODE, "");
    }


    public static String getDeviceSN() {
        String serial = null;
        try {
            Class<?> c = Class.forName("android.os.SystemProperties");
            Method get = c.getMethod("get", String.class);
            serial = (String) get.invoke(c, /*"ro.serialno"*/"persist.sys.serialno");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return serial;
        //return "D7W5011602GML469050000LC";
    }


    public static final String ACTION_REQUEST_SHUTDOWN = "android.intent.action.ACTION_REQUEST_SHUTDOWN";

    public static final String EXTRA_KEY_CONFIRM = "android.intent.extra.KEY_CONFIRM";

    public static void shutDownDevice(Context context) {
        SPUtil.put(context, Constants.SP_KEY_SLEEP_VALUE, "");
        // 创建Intent,如果要重启，则使用 Intent.ACTION_REBOOT
        Intent shutdownIntent = new Intent(ACTION_REQUEST_SHUTDOWN);

        // 这里设置的是：是否需要用户确认，若不需要，可以不设置或设置为false
        shutdownIntent.putExtra(EXTRA_KEY_CONFIRM, false);
        // 当作新任务执行
        shutdownIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        //启动Activity
        context.startActivity(shutdownIntent);
    }

    public static void startAlarm(Context context, int time) {
        int minuteCount = time * 1000 * 60; //minute
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(Constants.ACTION_POWER_OFF);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        if (Build.VERSION.SDK_INT < 19) {
            alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + minuteCount, pendingIntent);
        } else {
            alarmManager.setExact(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + minuteCount, pendingIntent);
        }
    }

    public static void cancelAlarm(Context context) {
        String sleepValue = (String) SPUtil.get(context, Constants.SP_KEY_SLEEP_VALUE, "");
        int minuteCount = 0;
        if (!TextUtils.isEmpty(sleepValue)) {
            minuteCount = Integer.parseInt(sleepValue.substring(0, 1)) * 1000 * 60;
        }
        Intent intent = new Intent(Constants.ACTION_POWER_OFF);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        alarmManager.cancel(pendingIntent);
    }


    private final static String[][] WAIT_CMDS = {
            {"mstar.videoadvert.finished", "0", "1"},//628、638、648
            {"sys.bootanimation.responsekey", "0", "1"},//5507
            {"third.finish.bootvideo.count", "0", "1"},//551
            {"third.get.bootvideo.end", "0", "1"}//553
    };

    public static void waitBootComplete() {
        try {
            if (new File("/data/showupdatetip").createNewFile()) {

            }
        } catch (Exception e1) {
            // TODO Auto-generated catch block
        }

        int times = 10000;
        do {
            try {
                for (String[] cmd : WAIT_CMDS) {
                    String key = cmd[0];
                    String def = cmd[1];
                    String result = cmd[2];

                    //LogUtil.v("SysProp.get("+ UVCKey +", " + def + ") = " + SysProp.get(UVCKey, def));
                    if (result.equals(getProp(key, def))) {
                        Log.d(Constants.LOG_TAG, "result.equals(get(key, def)) return");
                        return;
                    }
                }
                Thread.sleep(100);
            } catch (Exception e) {
                Log.d(Constants.LOG_TAG, "wait error = " + e.getMessage());
                e.printStackTrace();
            }
            Log.d(Constants.LOG_TAG, "wait times = " + times);
        } while (times-- > 0);
    }

    public static String getProp(String key, String defaultValue) {
        String value = defaultValue;
        try {
            Class c = Class.forName("android.os.SystemProperties");
            Method get = c.getMethod("get", String.class, String.class);
            value = (String) (get.invoke(c, key, defaultValue));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return value;
    }

    public static String getDeviceModel() {
        /*String value = getProp("ro.product.model", "");
        if(!TextUtils.isEmpty(value)) {
            if(value.contains("ChangHong")) {
                return "CH65";
            } else {
                return "TCL65";
            }
        } else {
            return "";
        }*/
        return "CH65";
    }

    public static int getNetType(Context context) {
        //0 有线网络
        //1 无线网络
        return Settings.Secure.getInt(context.getContentResolver(), "PROV_network_Select", 0);
    }

    /**
     * 获取当前本地apk的版本
     *
     * @param mContext
     * @return
     */
    public static int getVersionCode(Context mContext) {
        int versionCode = 0;
        try {
            //获取软件版本号，对应AndroidManifest.xml下android:versionCode
            versionCode = mContext.getPackageManager().
                    getPackageInfo(mContext.getPackageName(), 0).versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }

    /**
     * 获取版本号名称
     *
     * @param context 上下文
     * @return
     */
    public static String getVerName(Context context) {
        String verName = "";
        try {
            verName = context.getPackageManager().
                    getPackageInfo(context.getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return verName;
    }
}
